package com.example.selfcontrol.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.selfcontrol.dto.CommentDTO;
import com.example.selfcontrol.entity.Comment;
import com.example.selfcontrol.entity.User;
import com.example.selfcontrol.entity.resp.CommentResponse;
import com.example.selfcontrol.mapper.CommentMappper;
import com.example.selfcontrol.mapper.UserMapper;
import com.example.selfcontrol.service.CommentService;
import com.example.selfcontrol.config.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.example.selfcontrol.entity.resp.CommentResponse.CreateCommentResponse;

@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentMappper commentMappper ;
    @Autowired
    private UserMapper userMapper ;
    @Override
    public List<CommentDTO> getComments(Integer id) {

        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("attach_article",id) ;
        List<Comment>  comments = commentMappper.selectList(queryWrapper) ;

        List<CommentDTO> ans = new ArrayList<>() ;
        for(Comment item : comments) {
            // 获取评论的用户信息
            Long attach_user_id = item.getUserId();
            User user = userMapper.selectById(attach_user_id) ;

            // 获取评论的子评论
            Long commentId = item.getId() ;
            QueryWrapper<Comment> find = new QueryWrapper<>() ;
            find.eq("root_comment_id",commentId) ;
            List<Comment> subComments = commentMappper.selectList(find) ;

            // 装配子评论DTO （CommentResponse）
            List<CommentResponse> subList = new ArrayList<>() ;
            for(Comment subComment : subComments) {
                Long userId = subComment.getUserId()  ;
                User tmp_user = userMapper.selectById(userId) ;
                CommentResponse commentResponse = CommentResponse.CreateCommentResponse(tmp_user,subComment) ;

                subList.add(commentResponse) ;
            }

            // 装载CommentDTO
            CommentDTO commentDTO = new CommentDTO(item.getId(),item.getContent(),item.getCreatetime(),
                    item.getAttachArticle(),user.getNickName(),user.getPicture(),subList) ;
            ans.add(commentDTO) ;
        }

        return ans ;
    }

    @Override
    public Response sendComments(Comment comment) {
        try {
            commentMappper.insert(comment) ;
        } catch(Exception e) {
            e.printStackTrace();
            return Response.fail() ;
        }
       return Response.ok();
    }
}
